// lib/screens/post/publish_post_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; // 导入 services.dart 用于访问剪贴板

import '../../api/post_api.dart';       // 导入帖子API
import '../../api/community_api.dart';   // 导入社区API
import '../../models/community.dart';    // 导入社区模型

class PublishPostScreen extends StatefulWidget {
  const PublishPostScreen({super.key});

  @override
  State<PublishPostScreen> createState() => _PublishPostScreenState();
}

class _PublishPostScreenState extends State<PublishPostScreen> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();

  final PostApi _postApi = PostApi();
  final CommunityApi _communityApi = CommunityApi();

  List<Community> _communities = []; // 存储获取到的社区列表
  Community? _selectedCommunity;     // 当前选中的社区

  bool _isLoadingCommunities = true; // 社区列表是否正在加载
  bool _isPublishing = false;        // 帖子是否正在发布
  String? _errorMessage;             // 错误信息

  // 用于内容格式切换
  bool _isMarkdown = false; // true 表示 Markdown，false 表示纯文本

  @override
  void initState() {
    super.initState();
    _fetchCommunities(); // 页面初始化时获取社区列表
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    super.dispose();
  }

  /// 获取社区列表
  Future<void> _fetchCommunities() async {
    setState(() {
      _isLoadingCommunities = true;
      _errorMessage = null; // 清除之前的错误信息
    });
    try {
      final response = await _communityApi.getCommunities();
      if (response.code == 1000) { // 假设成功代码是 1000
        setState(() {
          _communities = response.data ?? [];
          // 如果有社区数据，默认选中第一个
          if (_communities.isNotEmpty) {
            _selectedCommunity = _communities.first;
          }
        });
      } else {
        setState(() {
          _errorMessage = response.msg ?? '获取社区列表失败';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = '加载社区列表异常: $e';
      });
    } finally {
      setState(() {
        _isLoadingCommunities = false;
      });
    }
  }

  /// 发布帖子
  Future<void> _publishPost() async {
    // 检查输入和社区选择
    if (_titleController.text.trim().isEmpty) {
      _showSnackBar('请输入帖子标题。');
      return;
    }
    if (_contentController.text.trim().isEmpty) {
      _showSnackBar('请输入帖子内容。');
      return;
    }
    if (_selectedCommunity == null || _selectedCommunity!.communityId == null) {
      _showSnackBar('请选择一个社区。');
      return;
    }

    setState(() {
      _isPublishing = true;
      _errorMessage = null; // 清除之前的错误信息
    });

    try {
      final response = await _postApi.createPost(
        title: _titleController.text.trim(),
        content: _contentController.text.trim(),
        communityId: _selectedCommunity!.communityId!,
      );

      if (response.code == 1000) {
        _showSnackBar('帖子发布成功！');
        Navigator.of(context).pop(); // 返回上一页 (通常是首页)
      } else {
        setState(() {
          _errorMessage = response.msg ?? '发布失败';
        });
        _showSnackBar('发布失败: ${_errorMessage!}');
      }
    } catch (e) {
      setState(() {
        _errorMessage = '发布异常: $e';
      });
      _showSnackBar('发布异常: $_errorMessage');
    } finally {
      setState(() {
        _isPublishing = false;
      });
    }
  }

  /// 显示 SnackBar 提示
  void _showSnackBar(String message) {
    if (mounted) { // 确保组件仍在挂载
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message)),
      );
    }
  }

  /// 粘贴剪贴板内容到内容输入框
  Future<void> _pasteContent() async {
    final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
    if (data != null && data.text != null) {
      final String currentText = _contentController.text;
      final int selectionStart = _contentController.selection.start;
      final int selectionEnd = _contentController.selection.end;

      String newText;
      if (selectionStart >= 0 && selectionEnd >= 0 && selectionStart <= currentText.length) {
        // 如果有选区，替换选区内容
        newText = currentText.replaceRange(selectionStart, selectionEnd, data.text!);
      } else {
        // 否则，在当前光标位置插入
        newText = currentText.substring(0, selectionStart) + data.text! + currentText.substring(selectionStart);
      }

      _contentController.value = _contentController.value.copyWith(
        text: newText,
        selection: TextSelection.collapsed(offset: selectionStart + data.text!.length),
      );
      _showSnackBar('内容已粘贴。');
    } else {
      _showSnackBar('剪贴板中没有文本内容。');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('发布帖子'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              TextField(
                controller: _titleController,
                decoration: const InputDecoration(
                  labelText: '标题',
                  hintText: '输入帖子标题',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.title),
                ),
                maxLength: 100,
              ),
              const SizedBox(height: 16),

              // 文本格式切换和粘贴按钮
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween, // 使子组件两端对齐
                children: [
                  // 格式切换按钮
                  ToggleButtons(
                    isSelected: [_isMarkdown == false, _isMarkdown == true], // 纯文本, Markdown
                    onPressed: (int index) {
                      setState(() {
                        _isMarkdown = index == 1; // 0 为纯文本, 1 为 Markdown
                      });
                    },
                    borderRadius: BorderRadius.circular(8.0),
                    selectedColor: Colors.white,
                    fillColor: Theme.of(context).primaryColor,
                    color: Theme.of(context).primaryColor,
                    borderColor: Theme.of(context).primaryColor,
                    selectedBorderColor: Theme.of(context).primaryColor,
                    children: const <Widget>[
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.0),
                        child: Text('TXT'),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.0),
                        child: Text('MD'),
                      ),
                    ],
                  ),
                  // 粘贴按钮
                  IconButton(
                    icon: const Icon(Icons.paste),
                    onPressed: _pasteContent,
                    tooltip: '粘贴内容',
                  ),
                ],
              ),
              const SizedBox(height: 8), // 调整间距

              TextField(
                controller: _contentController,
                decoration: InputDecoration(
                  labelText: _isMarkdown ? '内容 (Markdown)' : '内容 (纯文本)',
                  hintText: _isMarkdown
                      ? '支持 Markdown 语法，例如 # 标题, **粗体**, *斜体*, `代码`...'
                      : '写下你的帖子内容...',
                  border: const OutlineInputBorder(),
                  alignLabelWithHint: true,
                  prefixIcon: _isMarkdown ? const Icon(Icons.code) : const Icon(Icons.description),
                ),
                maxLines: 10,
                minLines: 5,
              ),
              const SizedBox(height: 16),
              // 社区选择下拉菜单
              _isLoadingCommunities
                  ? const Center(child: CircularProgressIndicator())
                  : _errorMessage != null
                  ? Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: Text(
                  '加载社区失败: $_errorMessage',
                  style: const TextStyle(color: Colors.red),
                ),
              )
                  : _communities.isEmpty
                  ? const Padding(
                padding: EdgeInsets.symmetric(vertical: 8.0),
                child: Text('暂无可用社区，请稍后再试或联系管理员。'),
              )
                  : DropdownButtonFormField<Community>(
                value: _selectedCommunity,
                decoration: const InputDecoration(
                  labelText: '选择社区',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.group),
                ),
                items: _communities.map((community) {
                  return DropdownMenuItem<Community>(
                    value: community,
                    child: Text(community.communityName ?? '未知社区'),
                  );
                }).toList(),
                onChanged: (Community? newValue) {
                  setState(() {
                    _selectedCommunity = newValue;
                  });
                },
                isExpanded: true,
                hint: const Text('请选择一个社区'),
                validator: (value) => value == null ? '请选择社区' : null,
              ),
              const SizedBox(height: 24),
              // 发布按钮
              _isPublishing
                  ? const Center(child: CircularProgressIndicator())
                  : ElevatedButton(
                onPressed: _publishPost,
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                child: const Text(
                  '发布帖子',
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
              ),
              if (_errorMessage != null && !_isLoadingCommunities && !_isPublishing)
                Padding(
                  padding: const EdgeInsets.only(top: 16.0),
                  child: Text(
                    '错误: $_errorMessage',
                    style: const TextStyle(color: Colors.red),
                    textAlign: TextAlign.center,
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }
}